package lil.llahn.security.common.asymmetric;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.util.Base64;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @ClassName: ECTool
 * @Description: TODO
 * @Date: 2019/11/8 16:04
 * @Auther: lil
 */
public class ECTool {
    private static final int EC_KEY_SIZE = 256;
    public static ConcurrentMap<Integer, String> keyMap = new ConcurrentHashMap<>(); // 非对称加密 key

    public static void main(String[] args) {
        genKeySpec();
        // 将公钥和私钥输出到日志
        System.out.println(String.format("生成的ECDSA公钥：%s", keyMap.get(0)));
        System.out.println(String.format("生成的ECDSA私钥：%s", keyMap.get(1)));
    }

    public static void genKeySpec() {
        try {
            //KeyPairGenerator类用于生成公钥和私钥对，基于EC算法生成对象
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(Algo.EC.name());
            //初始化密钥对生成器
            keyPairGen.initialize(EC_KEY_SIZE, new SecureRandom());
            // 生成一个密钥对，保存在keyPair中
            KeyPair keyPair = keyPairGen.generateKeyPair();
            ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();
            // 得到私钥
            ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
            // 得到公钥
            String publicKeyString = new String(Base64.getEncoder().encodeToString(publicKey.getEncoded()));
            // 得到私钥字符串
            String privateKeyString = new String(Base64.getEncoder().encodeToString((privateKey.getEncoded())));
            // 将公钥和私钥保存到Map
            keyMap.put(0, publicKeyString);// 0表示公钥
            keyMap.put(1, privateKeyString);// 1表示私钥
        }catch (Exception e){
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}
